from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from app01 import models
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from app01.utils.serializers import Camera_ser
import json
from rest_framework.views import APIView
from rest_framework.response import Response

class CameraEventListView(APIView):
    def get(self, request):
        events = models.CameraEvent.objects.all()
        serializer = Camera_ser.CameraEventSerializer(events, many=True)
        return Response({"status": True, "data": serializer.data})
class CameraListView(APIView):
    def get(self, request):
        cameras = models.Camera.objects.all()
        print(cameras)
        serializer = Camera_ser.CameraSerializer(cameras,many = True)
        
        data = {
            "data": serializer.data,
            "status": True  # 你可以根据需要设置这个字段的值
        }
        return Response(data)
    
    

@require_http_methods(["POST"])
@csrf_exempt
def camera_add_or_updata(request):
    try:
        data = json.loads(request.body)
        print(type(data))
        camera_id = data.get('id')
        video_url = data.get('url')
        gps_location = data.get('gps')
        if not camera_id or not video_url or gps_location is None:
            return JsonResponse({'status': 'error', 'message': 'Invalid input'}, status=400)
        camera, created = models.Camera.objects.update_or_create(
            camera_id=camera_id,
            defaults={
                'dangerous_behavior_video': video_url,
                'gps_location': gps_location
            }
        )
        if created:
            message = 'Created new record'
        else:
            message = 'Updated existing record'
        
        return JsonResponse({'status': 'success', 'message': message, 'camera_id': camera.camera_id, 'video_url': camera.dangerous_behavior_video, 'gps_location': camera.gps_location})
    
    except json.JSONDecodeError:
        return JsonResponse({'status': 'error', 'message': 'Invalid JSON'}, status=400)
    except Exception as e:
        print(str(e))
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

    
    
    
from django.http import JsonResponse
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from rest_framework.decorators import api_view
from rest_framework.response import Response

import json

@csrf_exempt
@api_view(['POST'])
def record_event(request):
    data = request.data
    camera_id = data.get('id')
    behavior = data.get('xinwei')
    illegal_items = data.get('weigui')
    person_name = data.get('renwu')
    # print(behavior)
    print(data)

    camera = get_object_or_404(models.Camera, camera_id=camera_id)

    # 创建新的摄像头事件
    event = models.CameraEvent.objects.create(
        camera=camera,
        behavior=behavior,
        illegal_items=illegal_items
    )

    # 如果识别到人物名字，更新对应学生的行为信息
    if person_name:
        student = get_object_or_404(models.Student, username=person_name)
        if not student.emotion_and_behavior:
            student.emotion_and_behavior = {}
        student.emotion_and_behavior[str(timezone.now())] = {"behavior": behavior}
        student.save()

    # 准备发送给前端的数据
    response_data = {
        'id': camera_id,
        'xinwei': behavior,
        'weigui': illegal_items,
    }

    # 通过 WebSocket 发送消息给前端
    from channels.layers import get_channel_layer
    from asgiref.sync import async_to_sync
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'events',
        {
            'type': 'send_event',
            'event': response_data,
        }
    )

    return Response({"status": "success"})